import { message } from "antd";
import Axios from "axios";
import {ServerUrl } from "../configs/AuthorizationServer";

const request = Axios.create({
  timeout: 15000,
  baseURL: "/api"
});

/**
 * 添加请求拦截器(在发送请求之前或之后做什么)
 */
request.interceptors.request.use(
    config => {
      const token = localStorage.getItem('authToken');
      if (token) {
        config.headers.Authorization = `bearer ${ token }`;
      }
      return config;
    },
    error => {
      return Promise.reject(error);
    }
);

/**
 * 添加响应拦截器
 */
request.interceptors.response.use(
    response => {
      return response;
    },
    error => {
      if (error.response) {
        if (error.response.status === 500) {
          if (error.response.data.message) {
            message.error("遇到其它错误，无法获取数据");
          } else {
            message.error("服务器错误");
            console.log(error.response.data);
          }
        }
        if (error.response.status === 504 || error.response.status === 404) {
          message.error("找不到服务器");
        }
        if (error.response.status === 401) {
          window.location.href = `${ServerUrl}/oauth/authorize?client_id=oauth&redirect_uri=${window.location.origin}/&response_type=code`;
        }
        return Promise.reject(error);
      } else {
        return Promise.reject(error);
      }
    }
);
export default request;
